"use strict";
Object.defineProperty(exports, "__esModule", {
  value: true
});
var SignerS3 = require("./signerS3");
var Parser = require("./xmldom/dom-parser")
var X2JS = require('./x2js/xml2json');

var OSSConfiguration = /** @class */ (function() {
  function OSSConfiguration(credentials, endPoint) {
    this.Creds = credentials;
    this.EndPoint = endPoint;
  }
  return OSSConfiguration;
}());
exports.OSSConfiguration = OSSConfiguration;

var OSS = /** @class */ (function() {
  function OSS(config) {
    this.endPoint = config.EndPoint;
    this.Creds = config.Creds;
    this.signer = new SignerS3.SignerS3(config.Creds);
  }
  OSS.prototype.PutObjectWithArrayBuffer = function(params, callback) {
    if (params.Buffer == null) {
      var err = {
        errMsg: "no buffer and filepath"
      }
      callback(err, null)
      return
    }
    var uri = "/" + params.Bucket + "/" + params.Key;
    var datetime = new Date().toUTCString();
    var authorization = this.signer.AuthorizationSignatureWithAcl("PUT", params.ContentType, params.Acl, datetime,
      uri);
    uni.request({
      method: 'PUT',
      url: this.endPoint + uri,
      data: params.Buffer,
      header: {
        'Content-Type': params.ContentType,
        'X-Amz-Date': datetime,
        'Authorization': authorization,
        'x-amz-acl': params.Acl,
        'X-Amz-User-Agent': 'aws-sdk-js/2.100.0 callback',
      },
      success(res) {
        if (res.statusCode == 200) {
          // var etag = res.header['ETag']
          // etag = etag.split('/').join('')
          res.data = 'http://' + params.Bucket + '/' + params.Key
          // var result = {
          //   ETag: etag
          // }
          // callback(null, result)
          callback(null, res)
        } else {
          var doc = new Parser.DOMParser().parseFromString(res.data);
          var result = new X2JS().xml2json(doc);
          var err = {
            errMsg: `ErrorCode: ${result.Error.Code}`,
            errCode: res.statusCode
          }
          callback(err, null)
        }
      },
      fail(err) {
        callback(err, null)
      }
    })
  };
  OSS.prototype.PutObject = function(params, callback) {
    if (params.Acl == undefined) {
      params.Acl = 'private'
    }
    if (params.ContentType == undefined) {
      params.ContentType = "application/octet-stream"
    }
    if (params.FilePath != null && params.FilePath != "") {
		uni.getFileSystemManager().readFile({
			filePath: params.FilePath,
			success: res => {
				params.Buffer = res.data;
				params.Key += ('.' + params.FilePath.split('.')[params.FilePath.split('.').length -1]);
				this.PutObjectWithArrayBuffer(params, callback)
			}
		});
    } else {
      this.PutObjectWithArrayBuffer(params, callback)
    }
  };
  return OSS;
}());
exports.OSS = OSS;
